'''
Created on 2011-10-26

@author: Administrator
'''
import os
import sqlite3
import urllib2
import datetime
from setting import *
from chart import *

def str2date(sdate):
    return sdate
    return datetime.date(int(sdate[:4]),int(sdate[4:6]),int(sdate[6:8]))
def int2date(s):
    sdate=str(s)
    if sdate.find('/')<0 and sdate.find('-')<0 :
        return datetime.date(int(sdate[:4]),int(sdate[4:6]),int(sdate[6:8]))
    sdate=sdate.replace('/','-')
    s=[]
    s=sdate.split('-')
    return datetime.date(int(s[0]),int(s[1]),int(s[2]))
def myfloat(src):
    if len(src)==0:return 0.0
    else: return float(src)
class StockByDateDB():
    def __init__(self,somedate):
        self.curdate=somedate
        dbfilename=os.path.join(stockbydatepath,str(somedate)+'.db3')
        self.db=sqlite3.connect(dbfilename)
        self.c=self.db.cursor()            
        self.createonetable('stocklist', ' (code text,open real,close real,high real,low real,yearhigh real,yearlow real,ma20 real,ma60 real,ma120 real,radio real,PRIMARY KEY (code))')
#        self.updatestockdata(datalist)
    def createonetable(self,tablename,para=''):
        sql='create table if not exists '+tablename+para
        self.c.execute(sql)
        self.db.commit() 
    def updatestockdata(self,datalist):
        if len(datalist)>0: 
            for r in datalist:                
                d=r
#                print 'd=',d
                sql='insert into stocklist (code,open,close,high,low,yearhigh,yearlow,ma20,ma60,ma120,radio) values(?,?,?,?,?,?,?,?,?,?,?)'
                self.c.execute(sql,(d[0],d[1],d[2],d[3],d[4],d[5],d[6],d[7],d[8],d[9],d[10]))
            self.db.commit()
    def focusdata(self):
        ret={}
        ret['ma120']=[['>120',0],['<120',0],['other',0]]
        ret['ma60']=[['>60',0],['<60',0],['other',0]]
        ret['ma20']=[['>20',0],['<20',0],['other',0]]
        ret['yearhighlow']=[['yearhigh',0],['yearlow',0],['other',0]]
        ret['2060120']=[['20>60>120',0],['20<60<120',0],['other',0]]
        
        sql='select code,close,high,low,ma20,ma60,ma120,yearhigh,yearlow from stocklist '
        self.c.execute(sql)
        result=self.c.fetchall()
        if result is None:return ret
        stocksum=len(result)
        for r  in result:
            (code,close,high,low,ma20,ma60,ma120,yearhigh,yearlow)=r
            print code
            #############################
            if ma20==0:ret['ma20'][2][1]=ret['ma20'][2][1]+1
            elif close>ma20:ret['ma20'][0][1]=ret['ma20'][0][1]+1
            else: ret['ma20'][1][1]=ret['ma20'][1][1]+1
            ############################
            if ma60==0:ret['ma60'][2][1]=ret['ma60'][2][1]+1
            elif close>ma60:ret['ma60'][0][1]=ret['ma60'][0][1]+1
            else: ret['ma60'][1][1]=ret['ma60'][1][1]+1
            ############################
            if ma120==0:ret['ma120'][2][1]=ret['ma120'][2][1]+1
            elif close>ma120:ret['ma120'][0][1]=ret['ma120'][0][1]+1
            else: ret['ma120'][1][1]=ret['ma120'][1][1]+1
            ############################
            if high>=yearhigh:ret['yearhighlow'][0][1]=ret['yearhighlow'][0][1]+1
            elif low<=yearlow:ret['yearhighlow'][1][1]=ret['yearhighlow'][1][1]+1
            else:ret['yearhighlow'][2][1]=ret['yearhighlow'][2][1]+1
            #########################################################
            if ma20> ma60 and ma60> ma120 and ma120>0:
                ret['2060120'][0][1]=ret['2060120'][0][1]+1
            elif ma120> ma60 and ma60> ma20 and ma20>0:
                ret['2060120'][1][1]=ret['2060120'][1][1]+1
            else:ret['2060120'][2][1]=ret['2060120'][2][1]+1
            ############################################
        return ret   
    def focusdataurl(self):
        result=self.focusdata()
        ret={}
        ct=Chart()
        for r in result.keys():
            ret[r]= ct.getchart_p(result[r],self.curdate)
        return ret
class StockDataDB():
    def __init__(self,job):
        if job.find('_')>0:(self.stockcode,self.reg)=job.split('_')
        if job.find(':')>0:(self.stockcode,self.reg)=job.split(':')
        self.job=job
        dbpath=os.path.join(stockdata_rootpath,self.reg)
#        if not os.path.exists(dbpath):os.mkdir(dbpath)
        dbfilename=os.path.join(dbpath,self.stockcode+'.db3')   
#        print 'dbfilename:',dbfilename
        if os.path.exists(dbfilename) :        
            self.db=sqlite3.connect(dbfilename)
            self.c=self.db.cursor()
        else:
            self.db=sqlite3.connect(dbfilename)
            self.c=self.db.cursor()            
            self.createonetable('kday', ' (date integer,open real,close real,high real,low real,yearhigh real,yearlow real,ma20 real,ma60 real,ma120 real,radio real,durations integer,PRIMARY KEY (date))')
    def createonetable(self,tablename,para=''):
        sql='create table if not exists '+tablename+para
        self.c.execute(sql)
        self.db.commit()     
    def calconestockdata(self,datalist):  
        dstdatalist={}
        sdc=StockDataCalc()
        for srconedata in sorted(datalist.keys()):
            
            oneresult=sdc.addoneday(datalist[srconedata])
#            print datalist[srconedata],oneresult
            dstdatalist[srconedata]=oneresult
        return dstdatalist
    def loaddata(self,startdate=0):
        if startdate==0:
            sql='select date,open,close,high,low,yearhigh,yearlow,ma20,ma60,ma120,radio from kday '
            self.c.execute(sql)
        else:
            sql='select date,open,close,high,low,yearhigh,yearlow,ma20,ma60,ma120,radio from kday where date>?'
            self.c.execute(sql,(startdate,))
        ret=self.c.fetchall()
        rlist=[]
        for r in ret:
            oneline=[]
            for e in r:
                oneline.append(e)
            rlist.append(oneline)
            
        return rlist
    def getdatabydate(self,somedate=''):
        if somedate=='':sql='select date,open,close,high,low,yearhigh,yearlow,ma20,ma60,ma120,radio from kday order by date desc limit 1'
        else:sql='select date,open,close,high,low,yearhigh,yearlow,ma20,ma60,ma120,radio from kday where date=?'
        self.c.execute(sql,(somedate,))
        ret=self.c.fetchone()
        return ret
    def updatestockdata(self):
        def getonestockdata():
            stockcode=self.stockcode
            stockdata={}
            content=open(os.path.join(rawcontentpath,self.job),'r').read()
            nlist=content.split('\n')
        #            print len(nlist)
            for n in nlist:
                t=n.split('"')
                if len(t)==5:
        #                    print t
                    stockdata[t[0]]=[t[0].strip(),round(myfloat(t[1].strip()),3),round(myfloat(t[2].strip()),3),round(myfloat(t[3].strip()),3),round(myfloat(t[4].strip()),3)]
            return stockdata
        #        print 'dblastdate:',dblastdate,dblastclose
        uprows=0
        #        if dblastdate==datetime.date.today():return uprows                    
        datalist={}
        datalistcalc={}
        datalist=getonestockdata()
        datalistcalc=self.calconestockdata(datalist)
#        print len(datalist)
        if len(datalist)>0: 
            for r in sorted(datalist.keys()):
                
                d=datalist[r]
                dr=datalistcalc[r]
#                print r,d,dr
                sql='insert into kday (date,open,close,high,low,yearhigh,yearlow,ma20,ma60,ma120,radio,durations) values(?,?,?,?,?,?,?,?,?,?,?,?)'
                self.c.execute(sql,(r,d[1],d[2],d[3],d[4],dr[0],dr[1],dr[2],dr[3],dr[4],dr[5],dr[6]))
                uprows=uprows+1
            self.db.commit()       
class StockDataCalc():
    #yearhigh ,yearlow ,ma20 ,ma60 ,ma120 ,radio ,durations
    def __init__(self):
        self.srcdatalist=[]
        self.dstdatalist=[]
        self.closelist=[]
        self.openlist=[]
        self.lowlist=[]
        self.highlist=[]
        self.datenum=0
    def getyearhighandlow(self):
        if self.datenum>54:
            yearhigh=max(self.highlist[self.datenum-54:])
            yearlow=min(self.lowlist[self.datenum-54:])
        else:
            yearhigh=max(self.highlist)
            yearlow=min(self.lowlist)    
        return (yearhigh,yearlow)  
    def getma(self,v):
        mv=0
        if self.datenum<v:return mv
        return round(sum(self.closelist[self.datenum-v:])/v,3)
    def getradio(self):
#        print 'getradio:',self.datenum
        if self.datenum>1:
            pre=self.closelist[self.datenum-2]
#            print 'getradio:',pre,self.closelist[self.datenum-1]
            if pre==0:return 0
            else:
                return round(self.closelist[self.datenum-1]/pre-1,3)
        return 0
    def getdurations(self):
        return 0
    def addoneday(self,onedata):
#        print onedata     
        self.openlist.append(onedata[1])
        self.closelist.append(onedata[2])
        self.highlist.append(onedata[3])
        self.lowlist.append(onedata[4])
        self.datenum=self.datenum+1
        onedayresult=[]   
        for e in range(0,7):
            onedayresult.append(0.0)     
        if self.datenum==0:pass
        else:
            onedayresult[0],onedayresult[1]=self.getyearhighandlow()
            onedayresult[2]=self.getma(20)
            onedayresult[3]=self.getma(60)
            onedayresult[4]=self.getma(120)
            onedayresult[5]=self.getradio()
            onedayresult[6]=self.getdurations()          
           
        return onedayresult
    def calc(self):
        pass
if __name__ == '__main__':
    print 'this is stockdata run'
#    stockcode='00073_HK'
    somedate='20111104'
    sd=StockByDateDB(somedate)
    urllist={}
    urllist=sd.focusdataurl()
    fname='c:\\temp.html'
    f=open(fname,'w')
    f.write('<html><body>')
    for s in urllist.keys():
        f.write('<img src="')
        f.write (urllist[s])
        f.write('">')
        f.write('<br>')
    f.write('</body></html>')

#    sd.updatestockdata()
#    dlist=sd.getdatabydate('20111103')
#    dlist=sd.loaddata()
#    print dlist
    
